<template>
	<view>
		<u-row style="width: 100%">
			<u-col v-for="(item, index) in fileList" :key="index" :span="4">
				<view class="x-upload">
					<view :style="{
						position: 'relative',
							width: width + 'rpx',
							height: height + 'rpx',
							border
						}" :class="['u-m-b-20', 'u-radius-' + borderRadius]">
						<view style="position: relative;z-index: 0;" @click="previewMedia(item, index)">
							<x-image :src="showImage(item.type === 'video' ? dealVideo(item.fileUrl) : item.fileUrl, 'logo')"
								:style="{
								width: width + 'rpx',
								height: height + 'rpx'
							}" :mode="mode"></x-image>
							
							<view class="video-play-icon" v-if="item.type === 'video' && item.percent === 100">
								<image src="@/static/image/common/video_play.png" class="auto-img"></image>
							</view>
						</view>
						
						<view v-if="item.percent !== -1 && item.percent !== 100" class="common-title" :style="{
							width: width + 'rpx',
							height: height + 'rpx',
							border,
							background
						}" :class="['u-radius-' + borderRadius]">
							<Loading1></Loading1>
						</view>
						<view class="file-close" @click="deleteAction(index)">
							<u-icon name="close-circle-fill" color="#fc3229" size="40"></u-icon>
						</view>
					</view>

				</view>
			</u-col>

			<!-- 图片视频选择器 -->
			<u-col v-if="authUpload" :span="4">
				<view :class="['file-box u-m-b-20 flex-center-center', 'u-radius-' + borderRadius]" :style="{
					width: width + 'rpx',
					height: height + 'rpx',
					border,
					background,
				}" @click="selectBefore()">
					<view class="clear-flex u-text-center">
						<view class="flex-center-center">
							<u-icon name="plus" size="37" color="#999999"></u-icon>
						</view>
						<view v-if="showText" class="u-m-t-24 u-f-22 u-lh-34 color-grew">
							{{ lang_common['uploadImage' + (uploadVideo ? 'Video' : '')] }}
						</view>
					</view>
				</view>
			</u-col>
		</u-row>
		
		<x-avatar ref="xavatar" @upload="uploadAction([$event.path])"
			avatarStyle="width: 0; height: 0;"></x-avatar>
		
		<!-- 图片视频选择弹窗 -->
		<x-popup v-model="fileTypeVisible" mode="bottom" z-index="9999999" @close="fileTypeVisible = false">
			<view class="bg-white">
				<view v-for="(item, index) in fileTypes" :key="index">
					<u-gap v-if="index" height="0.5" bg-color="rgba(151,151,151,.2)"></u-gap>
					<view class="u-f-30 u-lh-42 u-text-center" style="padding: 36rpx 0;width: 100%;"
						@click="changeFileAction(item)">{{ lang_common[item.key] }}
					</view>
				</view>
				<!-- 分割线 -->
				<u-gap height="8" bg-color="#F5F5F5"></u-gap>
				<view class="u-f-36 u-lh-50 flex-center-center" style="padding: 32rpx 0;"
					@click="fileTypeVisible = false">
					{{ lang_common.cancel }}
				</view>
			</view>
		</x-popup>
	</view>
</template>

<script>
	import upload from '@/utils/upload.js'
	import dayjs from 'dayjs'
	import Loading1 from '../x-image/anime/loading-1.vue'

	export default {
		components: { Loading1 },
		props: {
			value: {
				default: ''
			},
			mode: {
				default: 'aspectFill'
			},
			imgcut: {
				default: false
			},
			showText: {
				default: true,
			},
			uploadVideo: {
				default: false
			},
			width: {
				default: 200
			},
			height: {
				default: 200
			},
			border: {
				default: '2rpx dashed #DDDDDD'
			},
			borderRadius: {
				default: 34
			},
			// 背景颜色
			background: {
				default: '#f5f5f5'
			},
			// 文件总个数
			fileCount: {
				default: 9
			},
			// 限制视频上传个数
			limitVideoCount: {
				default: 1
			},
			// 图片后缀
			imageTypes: {
				type: [Array, String],
				default: () => ["xbm", "tif", "pjp", "svgz", "jpg", "jpeg", "ico", "tiff", "gif", "svg", "jfif", "webp",
					"png", "bmp", "pjpeg", "avif"
				],
			},
			// 视频后缀
			videoTypes: {
				type: [Array, String],
				default: () => ["mp4", "swf", "avi", "flv", "mpg", "rm", "mov", "wav", "asf", "3gp", "mkv", "rmvb"],
			},
		},
		data() {
			return {
				fileList: [],
				uploadList: [],
				fileTypeVisible: false
			}
		},
		computed: {
			fileTypes() {
				let fileTypelist = [{
					key: 'image',
					label: '图片'
				}]
				let videoList = this.fileList.filter(item => item.type === 'video')
				if (videoList.length < this.limitVideoCount && this.uploadVideo && !this.fileList.length) {
					fileTypelist = [...fileTypelist, {
						key: 'video',
						label: "视频"
					}]
				}
				return fileTypelist
			},
			// 是否允许上传
			authUpload() {
				if (this.uploadVideo) {
					let videoList = this.fileList.filter(item => item.type === 'video')
					return videoList.length < this.limitVideoCount
				} else {
					return this.fileCount > this.fileList.length
				}
			}
		},
		watch: {
			value: {
				handler(v) {
					v = v || ''
					let list = v.split(',') || [];
					let hasUpload = this.fileList.findIndex(item => item.percent !== 100) > -1
					if (!hasUpload) {
						this.fileList = list
							.map((item, index) => {
								if (item) {
									let [url, params] = item.split("?");
									let l = url.split(".");
									let type = l[l.length - 1].toLowerCase();
									let isImage = this.imageTypes.includes(type);
									let isVideo = this.videoTypes.includes(type);
									let cover = (params && params.split("cover=")[1]) || "";
									return {
										key: `${dayjs().valueOf()}-${index + 1000000}`,
										type: isVideo ? 'video' : 'image',
										percent: 100,
										fileUrl: url
									};
								}
								return "";
							})
							.filter((item) => item);
					}
				},
				immediate: true,
				deep: true
			}
		},
		methods: {
			// 处理视频
			dealVideo(url = '') {
				let arr = url.split('&cover=')
				return arr[arr.length - 1] || ''
			},
			// 查看图片
			previewMedia(item, index) {
				if (!item.fileUrl) return;
				if (item.type === 'video') {
					this.jumpUrl('/pages/other/videoshow/videoshow?url=' + encodeURIComponent(item.fileUrl))
				} else {
					uni.previewImage({
						urls: [this.baseUrl + item.fileUrl]
					})
				}
			},
			// 删除媒体资源
			deleteAction(index) {
				this.fileList.splice(index, 1)
				this.emitFile()
			},
			// 选择前
			selectBefore() {
				if (this.fileTypes.length < 2) {
					this.changeFileAction(this.fileTypes[0])
				} else {
					this.fileTypeVisible = true
				}
			},
			// 选择图片视频
			changeFileAction(item) {
				if (item.key === 'image') {
					if (this.imgcut) {
						let avatar = this.$refs.xavatar
						avatar.fChooseImg(1, {selWidth: "612upx", selHeight: "612upx", expWidth: "480upx", expHeight: "480upx", inner:true}, {data: 'xxx'});
						return
					}
					uni.chooseImage({
						sizeType: ['original'],
						count: this.fileCount,
						success: res => {
							this.uploadAction(res.tempFilePaths, 'image')
						},
						fail: e => {
							console.log(e)
							if (e.errMsg === 'chooseImage:fail No Permission') {
								this.$emit('fail', e)
							}
						}
					})
				} else {
					uni.chooseVideo({
						compressed: false,
						sourceType: ['album'],
						success: res => {
							this.uploadAction([res.tempFilePath], 'video')
						}
					})
				}
				this.fileTypeVisible = false
			},
			// 裁切返回的数据
			imgcutUpload(res) {
				console.log(res)
			},
			// 上传
			uploadAction(res = [], type = 'image') {
				console.log(res)
				let list = res.map((item, index) => {
					let result = {
						key: `${dayjs().valueOf()}-${index + 1000000}`,
						fileUrl: '',
						percent: 0,
						type
					}
					upload(({
						filePath: item,
						type: 'album'
					}), res => {
						let fileIndex = this.fileList.findIndex(file => file
							.key === result.key)
						if (fileIndex > -1) {
							this.$set(this.fileList[fileIndex], 'percent', res
								.progress)
							if (res.status === 'complete') {
								this.$set(this.fileList[fileIndex], 'fileUrl', res
									.msg.path)
								this.emitFile()
							}
						}
					}, 1)
					return result
				})
				this.fileList = [...this.fileList, ...list]
				console.log(this.fileList)
			},
			emitFile() {
				let list = [...this.fileList.filter(file => file.fileUrl)]
				let str = list.map(item => item.fileUrl).join(',')
				this.$emit('input', str)
				this.$emit('change', list)
			}
		}

	}
</script>

<style scoped lang="scss">
	.file {
		&-box {
			position: relative;
		}

		&-close {
			position: absolute;
			top: 10rpx;
			right: 10rpx;
			z-index: 999;
		}
	}

	.file-type {
		&-container {
			padding: 48rpx 36rpx calc(env(safe-area-inset-bottom) + 48rpx);
			border-top-left-radius: 40rpx;
			border-top-right-radius: 40rpx;
			background-color: #FFFFFF;
		}

		&-item {
			width: 200rpx;
			height: 72rpx;
			border-radius: 8rpx;
			background-color: rgba(245, 245, 245, 1);
		}
	}
	
	.video-play-icon {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		z-index: 10204;
		width: 100rpx;
		height: 100rpx;
	}
</style>
